#include "threadPool.h"
int exitPipe[2];
void handler(int signum){
    printf("signum = %d\n",signum);
    write(exitPipe[1],"1",1);
}
/* Usage:  */
int main(int argc, char *argv[]){ 

    pipe(exitPipe);
    if(fork()){
        close(exitPipe[0]);
        signal(SIGUSR1,handler);
        wait(NULL);
        printf("Parent is exiting!\n");
        exit(0);
    }
    close(exitPipe[1]);
    ARGS_CHECK(argc,4); 
    // 初始化线程池
    threadPool_t threadPool;
    int workerNum = atoi(argv[3]);
    int ret1 = threadPoolInit(&threadPool,workerNum);
    ERROR_CHECK(ret1,-1,"threadPoolInit");
    //压榨niger
    int ret2 = makeWorker(&threadPool);   
    ERROR_CHECK(ret2,-1,"makeWorker");
    // 初始化tcp连接和epoll
    int sockfd = tcpInit(argv[1],argv[2]);
    ERROR_CHECK(sockfd,-1,"tcpInit");
    int epfd = epoll_create(1);
    //sockfd加入监听
    int ret = epollAdd(epfd,sockfd);
    ERROR_CHECK(ret,-1,"epollAdd");
    epollAdd(epfd,exitPipe[0]);
    struct epoll_event readyset[1024];
    while(1){
        int readyNum = epoll_wait(epfd,readyset,1024,-1);
        ERROR_CHECK(readyNum,-1,"epoll_wait");
        for(int i = 0; i < readyNum; i++){
            if(readyset[i].data.fd == sockfd){
                int netfd = accept(sockfd,NULL,NULL);
                LOG_CHECK(netfd,"accept");
                ERROR_CHECK(netfd,-1,"accept");
                printf("[server]Notice: get the netfd :%d\n",netfd);
                pthread_mutex_lock(&threadPool.mutex);
                enQueue(&threadPool.taskQueue,netfd); // 将netfd加入任务队列,创建一个线程池中的线程。
                pthread_cond_broadcast(&threadPool.cond);
                pthread_mutex_unlock(&threadPool.mutex);
            }else if(readyset[i].data.fd == exitPipe[0]){
                printf("threadPool is exiting!\n");
                pthread_mutex_lock(&threadPool.mutex);
                threadPool.exitFlag = 1;
                pthread_cond_broadcast(&threadPool.cond);
                pthread_mutex_unlock(&threadPool.mutex);

                for(int j = 0; j < workerNum; j++){
                    pthread_join(threadPool.tidArr.arr[j],NULL);
                }
                printf("Master is going to exit\n");
                exit(0);
            }
        }
    }
    return 0;
}
